package com.lenovo.codestatreport.jira.service;

import com.lenovo.codestatreport.jira.mapper.IssuesMapper;
import com.lenovo.codestatreport.jira.model.Issues;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author Howie Lu
 * @version Created at 2019/05/20
 * @version Updated at 2019/05/21
 */
@Service
public class IssueServiceImpl implements IssueService{
    @Autowired
    IssuesMapper issuesMapper;
    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Override
    public List<Issues> getAllIssueRecords(String start, String end) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = "/From" + start + "to" + end;
        redisTemplate.setKeySerializer(redisSerializer);
        List<Issues> list = (List<Issues>) redisTemplate.opsForValue().get(key);
        if (list == null) {
            list = issuesMapper.selectAllIssueRecords(start, end);
            redisTemplate.opsForValue().set(key, list, 120, TimeUnit.SECONDS);
            //  System.out.println(key + " 缓存中没找到，访问数据库！");
        }// else System.out.println(key + " 缓存中找到了，无需访问数据库！");
        return list;
    }

    @Override
    public List<String> findIssuesInProject(String projectKey) {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        String key = "/IssuesInProject" + projectKey;
        redisTemplate.setKeySerializer(redisSerializer);
        List<String> list = (List<String>) redisTemplate.opsForValue().get(key);
        if (list == null) {
            list = issuesMapper.selectAllIssuesInProject(projectKey);
            redisTemplate.opsForValue().set(key, list, 120, TimeUnit.SECONDS);
            //  System.out.println(key + " 缓存中没找到，访问数据库！");
        }// else System.out.println(key + " 缓存中找到了，无需访问数据库！");
        return list;
    }
}
